package cn.xw.mq.producer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-13 23:30
 * 生产者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SimpleProducer {

    //注入RabbitTemplate对象
    private final RabbitTemplate rabbitTemplate;

    /***
     * 生产者方法
     * @param msg 生产者发送的消息
     */
    public void productionSimpleMessage(MessageSendDTO msg) {
        log.info("生产者接收到消息，并发送到Brock的交换机....");
        //消息转换为JSON格式发送，并发送到Brock的交换机
        byte[] bytes = JSONObject.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
        //convertAndSend("交换机名称","路由key","发送消息内容")，其实和原生的：
        // channel.basicPublish("交换机名称","路由key","其它参数","消息");
        // 使用convertAndSend默认消息是持久化的，如我们当初原生设置的 其它参数：MessageProperties.PERSISTENT_TEXT_PLAIN
//        rabbitTemplate.convertAndSend(RabbitMQConfig.SIMPLE_DIRECT_EXCHANGE, RabbitMQConfig.SIMPLE_KEY, bytes);
        rabbitTemplate.convertAndSend(RabbitMQConfig.SIMPLE_DIRECT_EXCHANGE, RabbitMQConfig.SIMPLE_KEY, bytes);
    }
}